package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.exception.QueryFailedException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.ProcessFlowService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.OrderUtil;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 类说明:
 * 
 * @author XIET
 * 
 * @version 创建时间：2018年12月6日 下午2:56:26
 */
@Service
public class ProcessFlowServiceImpl implements ProcessFlowService {

	private static final Logger logger = LoggerFactory.getLogger(ProcessFlowServiceImpl.class);
	/**
	 * 注入mapper
	 */
	@Resource
	private ProcessFlowMapper processFlowMapper;
	@Resource
	private ProcessTargetMapper processTargetMapper;

	@Resource
	private ProcessStaMapper processStaMapper;

	@Resource
	private ProcessBomMapper processBomMapper;
	@Resource
	private ProcessBlxxMapper processBlxxMapper;

	/**
	 * 查询工艺流程
	 */
	@Override
	public JSONObject queryProcessFlow(ProcessFlow processFlow) {
		// 声明listProcessFlow集合，用来装查询出来的参数
		List<ProcessFlow> listProcessFlow = null;
		ProcessFlow pFlow = null;
		try {
			Integer pagesize = processFlow.getPagesize();
			Integer pageindex = processFlow.getPageindex();
			if (pagesize != null && pageindex != null) {
				processFlow.setIncept(pagesize * (pageindex - 1));
			}
			// 获取工艺流程id
			Integer lProFlow = processFlow.getlProFlow();

//			if(!processFlow.getlProVer().equals(null)){
//				listProcessFlow = processFlowMapper.listProcessFlow(processFlow);
//
//			}
//			listProcessFlow = processFlowMapper.listProcessFlow(new ProcessFlow());

			if(processFlow.getlProVer()!=null){
				ProcessFlow sortFlow=new ProcessFlow();
				sortFlow.setlProVer(processFlow.getlProVer());
				List<ProcessFlow> sortList= processFlowMapper.listProcessFlow(sortFlow);
				Map<Integer,Integer> map=new HashMap<>();
				for (ProcessFlow p :sortList ) {
					map.put(p.getlProFlow(),p.getlOrder());
				}
				OrderUtil orderUtil=new OrderUtil();
				map=orderUtil.OrederSort(map);
				for(Map.Entry<Integer, Integer> entry : map.entrySet()){
					Integer mapKey = entry.getKey();
					Integer mapValue = entry.getValue();
					for (ProcessFlow p :sortList ) {
						if(p.getlProFlow().equals(mapKey)) {
							p.setlOrder(mapValue);
						}
					}
//					map.put(mapKey,i++);
//            System.out.println(mapKey+":"+mapValue);
				}
				for (ProcessFlow p :sortList ) {
					processFlowMapper.updateProcessFlow(p);
				}


			}

			// 判断lProFlow 是否存在，存在则是查询单个工艺流程

				listProcessFlow = processFlowMapper.listProcessFlow(processFlow);
				// 判断查询出来的集合是否为空
				if (listProcessFlow.isEmpty()) {
					return JSONObject.oK("没有相关数据", listProcessFlow, 0);
				}
				// 用来记录查询出来的条数
				int count = processFlowMapper.countProcessFlow(processFlow);
				return JSONObject.oK("查询成功", listProcessFlow, count);


		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 删除工艺流程
	 */
	@Override
	public JSONObject deleteProcessFlow(List<Integer> lProFlows, Integer lDataState) {
		try {
			// 判断传入的参数是否为null
			if (lDataState == null) {
				// 为null抛出异常
				throw new ParamsErrorException("数据状态不能为空");
			} else if (lDataState != 1 && lDataState != 2 && lDataState != 3) {
				throw new ParamsErrorException("数据状态错误");
			}
			if (lProFlows == null) {
				throw new ParamsErrorException("请选择要删除的工艺流程");
			}
			// 调用删除的接口
			int row = processFlowMapper.deleteProcessFlow(lProFlows, lDataState);
			if (row == 0) {
				throw new ModifyFailedException("操作失败");
			}

			return JSONObject.oK("操作成功");
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 新增工艺流程
	 */
	@Override
	public JSONObject insertProcessFlow(ProcessFlow processFlow) {
		try {
			// 判断传入的参数是否为null
			if (processFlow.getlProFlow() != null) {
				// 为null则抛出异常
				throw new ParamsErrorException("新增工艺流程不用传id");
			}
			if(processFlow.getlDataState()==null){
				processFlow.setlDataState(1);
			}
			if(processFlow.getWhetherSequence()==null){
				processFlow.setWhetherSequence(1);
			}


			// 调用新增接口
			int row = processFlowMapper.insertProcessFlow(processFlow);
			if (row == 0) {
				throw new QueryFailedException("新增失败");
			}
			return JSONObject.oK("新增成功", processFlow.getlProFlow());
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 修改工艺流程
	 */
	@Override
	public JSONObject updateProcessFlow(ProcessFlow processFlow) {
		try {
			// 判断传入的参数是否为null
			if (processFlow.getlProFlow() == null) {
				throw new ParamsErrorException("修改工艺流程需要传入id");
			}
			if(processFlow.getlDataState()==null){
				processFlow.setlDataState(1);
			}
			if(processFlow.getWhetherSequence()==null){
				processFlow.setWhetherSequence(1);
			}
			// 调用修改的接口
			int row = processFlowMapper.updateProcessFlow(processFlow);
			if (row == 0) {
				throw new QueryFailedException("修改失败");
			}
			return JSONObject.oK("修改成功");
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}







//上移
@Override
public JSONObject orderUp(ProcessFlow processFlow) {
	try {

		// 获取工艺流程id
		Integer lProFlow = processFlow.getlProFlow();
		if(processFlow.getlProVer()!=null){
			ProcessFlow sortFlow=new ProcessFlow();
			sortFlow.setlProVer(processFlow.getlProVer());
			List<ProcessFlow> sortList= processFlowMapper.listProcessFlow(sortFlow);
			Map<Integer,Integer> map=new HashMap<>();
			for (ProcessFlow p :sortList ) {
				map.put(p.getlProFlow(),p.getlOrder());
			}
			System.out.println("测试成功"+map+""+ processFlow.getlProFlow());
			OrderUtil orderUtil=new OrderUtil();
			map=orderUtil.OrederSort(map);
			System.out.println("测试成功"+map+""+ processFlow.getlProFlow());
			map=orderUtil.OrederSortUp(map, processFlow.getlProFlow());
			System.out.println("测试成功"+map+""+ processFlow.getlProFlow());
			for(Map.Entry<Integer, Integer> entry : map.entrySet()){
				Integer mapKey = entry.getKey();
				Integer mapValue = entry.getValue();
				for (ProcessFlow p :sortList ) {
					if(p.getlProFlow().equals(mapKey)) {
						p.setlOrder(mapValue);
					}
				}
			}
			for (ProcessFlow p :sortList ) {
				processFlowMapper.updateProcessFlow(p);
			}
		}
			return JSONObject.oK("上移成功");

	} catch (GlobalException e) {// 捕获自定义异常
		logger.error(e.getMessage());
		return JSONObject.build(500, e.getMessage());
	}
}
//下移
@Override
public JSONObject orderDown(ProcessFlow processFlow) {

	try {

		// 获取工艺流程id
		Integer lProFlow = processFlow.getlProFlow();

		if(processFlow.getlProVer()!=null){
			ProcessFlow sortFlow=new ProcessFlow();
			sortFlow.setlProVer(processFlow.getlProVer());
			List<ProcessFlow> sortList= processFlowMapper.listProcessFlow(sortFlow);
			Map<Integer,Integer> map=new HashMap<>();
			for (ProcessFlow p :sortList ) {
				map.put(p.getlProFlow(),p.getlOrder());
			}
			System.out.println("测试成功"+map+""+processFlow.getlProFlow());
			OrderUtil orderUtil=new OrderUtil();
			map=orderUtil.OrederSort(map);
			System.out.println("测试成功"+map+""+processFlow.getlProFlow());
			map=orderUtil.OrederSortDown(map,processFlow.getlProFlow());
			System.out.println("测试成功"+map+""+processFlow.getlProFlow());
			for(Map.Entry<Integer, Integer> entry : map.entrySet()){
				Integer mapKey = entry.getKey();
				Integer mapValue = entry.getValue();
				for (ProcessFlow p :sortList ) {
					if(p.getlProFlow().equals(mapKey)) {
						p.setlOrder(mapValue);
					}
				}
			}
			for (ProcessFlow p :sortList ) {
				processFlowMapper.updateProcessFlow(p);
			}

		}

		return JSONObject.oK("下移成功");
	} catch (GlobalException e) {// 捕获自定义异常
		logger.error(e.getMessage());
		return JSONObject.build(500, e.getMessage());
	}
}

	@Override
	public JSONObject batchInsertProcessFlow( List<Integer> lProIds, Integer lProVer) {
		try {
			// 判断传入的参数是否为null

			if(lProIds==null){
				throw new ParamsErrorException("工序id不能为空");
			}
			if(lProVer==null){
				throw new ParamsErrorException("版本id不能为空");
			}
			int row = 0;
			for (int i=0;i<lProIds.size();i++){
				ProcessFlow processFlow1=new ProcessFlow();
				processFlow1.setlProId(lProIds.get(i));
				processFlow1.setlProVer(lProVer);
				processFlow1.setlDataState(1);
				processFlow1.setWhetherSequence(1);
				row =row+ processFlowMapper.insertProcessFlow(processFlow1);
			}




			// 调用新增接口

			if (row == 0) {
				throw new QueryFailedException("新增失败");
			}
			return JSONObject.oK("新增成功",row);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}
		//保存
	@Override
	public JSONObject saveProcessFlow(List<ProcessFlow> processFlowList) {
		try {
			//获取数据数据版本id
			if(processFlowList==null){
				throw new ParamsErrorException("流程不能为空");
			}

			Integer lProVer=processFlowList.get(0).getlProVer();
			if(lProVer==null){
				throw new ParamsErrorException("版本id不能为空");
			}
			//获取数据库数据
			ProcessFlow processFlow1=new ProcessFlow();
			processFlow1.setlProVer(lProVer);
			List<ProcessFlow> oldprocessFlowList=processFlowMapper.listProcessFlow(processFlow1);
			List<Integer> deleteList = DeleteList(oldprocessFlowList, processFlowList);
			int deleterow=0;
			int insertrow=0;
			int updaterow=0;
			if(deleteList.size()!=0){
				deleterow = processFlowMapper.deleteProcessFlow(deleteList, 2);
			}


			//删除完成  进行新增 和 修改
			for (ProcessFlow processFlow:processFlowList
				 ) {
				if(processFlow.getlDataState()!=null){
					processFlow.setlDataState(1);
				}

				if(processFlow.getlProFlow()!=null){
					if(processFlow.getlProFlow().equals(0)){
						processFlow.setlProFlow(null);

						insertrow=insertrow+processFlowMapper.insertProcessFlow(processFlow);

					}else{
						updaterow=updaterow+processFlowMapper.updateProcessFlow(processFlow);
					}


				}
			}




			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject saveProcessTarget(ProcessFlow processFlow) {
		try {
			//获取数据数据版本id
			if(processFlow==null){
				throw new ParamsErrorException("流程不能为空");
			}
			Integer lProFlow=processFlow.getlProFlow();
			if(lProFlow==null){
				throw new ParamsErrorException("流程id不能为空");
			}
			//获取前端数据
			List<ProcessTarget> processTargetList=processFlow.getProcessTargetList();


			//获取数据库数据
			ProcessTarget processTarget1=new ProcessTarget();
			processTarget1.setlProFlow(lProFlow);
			List<ProcessTarget> oldprocessTargetList=processTargetMapper.queryProcessTarget(processTarget1);

			//找出要删除的数据
			List<Integer> processTargetIds=new ArrayList<>();
			List<Integer> oldIds=new ArrayList<>();
			List<Integer>newIds=new ArrayList<>();
			for (ProcessTarget processTarget:oldprocessTargetList
			) {
				oldIds.add(processTarget.getlProTarget());
			}

			if(processTargetList!=null) {
				for (ProcessTarget processTarget : processTargetList
				) {
					newIds.add(processTarget.getlProTarget());
				}
			}
			HashSet h1 = new HashSet(oldIds);
			HashSet h2 = new HashSet(newIds);
			h1.removeAll(h2);
			processTargetIds.addAll(h1);

			int deleterow=0;
			int insertrow=0;
			int updaterow=0;

			if(processTargetIds.size()!=0){

				deleterow = processTargetMapper.deleteProcessTarget(processTargetIds, 2);
			}


			//删除完成  进行新增 和 修改
			for (ProcessTarget processTarget:processTargetList
			) {
				if(processTarget.getlDataState()==null){
					processTarget.setlDataState(1);
				}
				if(processTarget.getlProTarget()!=null){
					if(processTarget.getlProTarget().equals(0)){
						processTarget.setlProTarget(null);
						Integer Counts = processTargetMapper.checkProcessTarget(processTarget);
						if (Counts ==0) {
							insertrow=insertrow+processTargetMapper.insertProcessTarget(processTarget);
						}

					}else{
						Integer Counts = processTargetMapper.checkProcessTarget(processTarget);
						if (Counts ==0) {
							updaterow = updaterow + processTargetMapper.updateProcessTarget(processTarget);
						}
					}


				}
			}



			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject saveProcessSta(ProcessFlow processFlow) {
		try {
			//获取数据数据版本id
			if(processFlow==null){
				throw new ParamsErrorException("流程不能为空");
			}
			Integer lProFlow=processFlow.getlProFlow();
			if(lProFlow==null){
				throw new ParamsErrorException("流程id不能为空");
			}
			//获取前端数据
			List<ProcessSta> processStaList=processFlow.getProcessStaList();


			//获取数据库数据
			ProcessSta processSta1=new ProcessSta();
			processSta1.setlProFlow(lProFlow);
			List<ProcessSta> oldprocessStaList=processStaMapper.queryProcessSta(processSta1);

			//找出要删除的数据
			List<Integer> processStaIds=new ArrayList<>();
			List<Integer> oldIds=new ArrayList<>();
			List<Integer>newIds=new ArrayList<>();
			for (ProcessSta processSta:oldprocessStaList
			) {
				oldIds.add(processSta.getProcessStaId());
			}
			if(processStaList!=null) {
				for (ProcessSta processSta : processStaList
				) {
					newIds.add(processSta.getProcessStaId());
				}
			}
			HashSet h1 = new HashSet(oldIds);
			HashSet h2 = new HashSet(newIds);
			h1.removeAll(h2);
			processStaIds.addAll(h1);

			int deleterow=0;
			int insertrow=0;
			int updaterow=0;
			if(processStaIds.size()!=0){

				deleterow = processStaMapper.deleteProcessSta(processStaIds, 2);
			}


			//删除完成  进行新增 和 修改
			for (ProcessSta processSta:processStaList
			) {
				if(processSta.getDataState()==null){
					processSta.setDataState(1);
				}
				if(processSta.getProcessStaId()!=null){
					if(processSta.getProcessStaId().equals(0)){
						processSta.setProcessStaId(null);

						Integer Counts = processStaMapper.checkProcessSta(processSta);
						if (Counts ==0) {
							insertrow = insertrow + processStaMapper.insertProcessSta(processSta);
						}

					}else{
						Integer Counts = processStaMapper.checkProcessSta(processSta);
						if (Counts ==0) {
							updaterow = updaterow + processStaMapper.updateProcessSta(processSta);
						}
					}


				}
			}



			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject saveProcessBom(ProcessFlow processFlow) {
		try {
			//获取数据数据版本id
			if(processFlow==null){
				throw new ParamsErrorException("流程不能为空");
			}
			Integer lProFlow=processFlow.getlProFlow();
			if(lProFlow==null){
				throw new ParamsErrorException("流程id不能为空");
			}
			//获取前端数据
			List<ProcessBom> processBomList=processFlow.getProcessBomList();


			//获取数据库数据
			ProcessBom processBom1=new ProcessBom();
			processBom1.setlProFlow(lProFlow);
			List<ProcessBom> oldprocessBomList=processBomMapper.queryProcessBom(processBom1);

			//找出要删除的数据
			List<Integer> processBomIds=new ArrayList<>();
			List<Integer> oldIds=new ArrayList<>();
			List<Integer>newIds=new ArrayList<>();
			for (ProcessBom processBom:oldprocessBomList
			) {
				oldIds.add(processBom.getProcessBomId());
			}
			if(processBomList!=null){
			for (ProcessBom processBom:processBomList
			) {
				newIds.add(processBom.getProcessBomId());
			}}
			HashSet h1 = new HashSet(oldIds);
			HashSet h2 = new HashSet(newIds);
			h1.removeAll(h2);
			processBomIds.addAll(h1);

			int deleterow=0;
			int insertrow=0;
			int updaterow=0;
			if(processBomIds.size()!=0){

				deleterow = processBomMapper.deleteProcessBom(processBomIds, 2);
			}


			//删除完成  进行新增 和 修改
			for (ProcessBom processBom:processBomList
			) {
				if(processBom.getDataState()==null){
					processBom.setDataState(1);
				}
				if(processBom.getProcessBomId()!=null){
					if(processBom.getProcessBomId().equals(0)){
						processBom.setProcessBomId(null);
						Integer Counts = processBomMapper.checkProcessBom(processBom);
						if (Counts ==0) {
							insertrow = insertrow + processBomMapper.insertProcessBom(processBom);
						}

					}else{
						Integer Counts = processBomMapper.checkProcessBom(processBom);
						if (Counts ==0) {
							updaterow = updaterow + processBomMapper.updateProcessBom(processBom);
						}
					}


				}
			}



			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject saveProcessBlxx(ProcessFlow processFlow) {
		try {
			//获取数据数据版本id
			if(processFlow==null){
				throw new ParamsErrorException("流程不能为空");
			}
			Integer lProFlow=processFlow.getlProFlow();
			if(lProFlow==null){
				throw new ParamsErrorException("流程id不能为空");
			}
			//获取前端数据
			List<ProcessBlxx> processBlxxList=processFlow.getProcessBlxxList();


			//获取数据库数据
			ProcessBlxx processBlxx1=new ProcessBlxx();
			processBlxx1.setlProFlow(lProFlow);
			List<ProcessBlxx> oldprocessBlxxList=processBlxxMapper.queryProcessBlxx(processBlxx1);

			//找出要删除的数据
			List<Integer> processBlxxIds=new ArrayList<>();
			List<Integer> oldIds=new ArrayList<>();
			List<Integer> newIds=new ArrayList<>();
			for (ProcessBlxx processBlxx:oldprocessBlxxList
			) {
				oldIds.add(processBlxx.getProcessBlxxId());
			}
			if(processBlxxList!=null){
			for (ProcessBlxx processBlxx:processBlxxList
			) {
				newIds.add(processBlxx.getProcessBlxxId());
			}}
			HashSet h1 = new HashSet(oldIds);
			HashSet h2 = new HashSet(newIds);
			h1.removeAll(h2);
			processBlxxIds.addAll(h1);

			int deleterow=0;
			int insertrow=0;
			int updaterow=0;
			if(processBlxxIds.size()!=0){

				deleterow = processBlxxMapper.deleteProcessBlxx(processBlxxIds, 2);
			}


			//删除完成  进行新增 和 修改
			for (ProcessBlxx processBlxx:processBlxxList
			) {
				if(processBlxx.getDataState()==null){
					processBlxx.setDataState(1);
				}
				if(processBlxx.getProcessBlxxId()!=null){
					if(processBlxx.getProcessBlxxId().equals(0)){
						processBlxx.setProcessBlxxId(null);
						Integer Counts = processBlxxMapper.checkProcessBlxx(processBlxx);
						if (Counts ==0) {
							insertrow = insertrow + processBlxxMapper.insertProcessBlxx(processBlxx);
						}
					}else{
						Integer Counts = processBlxxMapper.checkProcessBlxx(processBlxx);
						if (Counts ==0) {
							updaterow = updaterow + processBlxxMapper.updateProcessBlxx(processBlxx);
						}
					}


				}
			}



			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	//删除不存在的数据
	private List<Integer> DeleteList(List<ProcessFlow> oldprocessFlowList, List<ProcessFlow> processFlowList) {
		List<Integer> processFlowIds=new ArrayList<>();
		List<Integer> oldIds=new ArrayList<>();
		for (ProcessFlow processFlow:oldprocessFlowList
			 ) {
			oldIds.add(processFlow.getlProFlow());
		}
		List<Integer>newIds=new ArrayList<>();
		for (ProcessFlow processFlow:processFlowList
		) {
			newIds.add(processFlow.getlProFlow());
		}
		HashSet h1 = new HashSet(oldIds);
		HashSet h2 = new HashSet(newIds);
		h1.removeAll(h2);
		processFlowIds.addAll(h1);
		return processFlowIds;

	}


}
